package com.teacher.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.model.BaseUser;
import com.common.model.Profession;
import com.common.model.Project;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.common.util.Md5Encrypt;
import com.student.model.IntentProject;
import com.teacher.model.ProjAndProf;
import com.teacher.model.TeachCourse;
import com.teacher.service.TeacherService;
import com.teacher.util.DBToExcel;
import com.teacher.util.ExcelUtils;
import com.teacher.util.POIWordToHtml;
import com.teacher.util.StringUtils;
import com.teacher.util.Upload;

/**
 * 负责控制教师版块的页面跳转
 * 
 * @author XHFSJ
 * 
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

	private static final Logger log = org.slf4j.LoggerFactory
			.getLogger(TeacherController.class);
	private final String SUCCESS = "success";
	private final String FAIL = "fail";
	private final String TITLE = "title";
	private String[] importCols;
	public String[] getImportCols() {
		return importCols;
	}

	public void setImportCols(String[] importCols) {
		this.importCols = importCols;
	}

	@Autowired
	private TeacherService tservice;

	/**
	 * 以ajax方式处理密码修改过程
	 * 
	 * @param password
	 *            新密码
	 * @param request
	 * @return 如果密码修改失败，则返回"failed",反之返回“success”
	 */
	@RequestMapping("/modify_password")
	@ResponseBody
	public String UpdateTeacherPassword(
			@RequestParam("password") String password,
			HttpServletRequest request) {
		String tea_no = ((TeacherUser) request.getSession()
				.getAttribute("user")).getNo();
		boolean Oper_result = tservice.UpdateTeacherPassword(password, tea_no);
		request.getSession().removeAttribute("user");
		return Oper_result ? SUCCESS : FAIL;
	}

	/**
	 * 跳转至密码修改页面
	 * 
	 * @return
	 */
	@RequestMapping("/show_modify_password")
	public ModelAndView ShowModifyPasswordPage() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("title", "教师密码维护");
		mav.setViewName("teacher/modify_password");
		return mav;
	}

	/**
	 * 跳转至个人信息管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/update_info")
	public ModelAndView ToManagePersonalInformation(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("teacher/update_info");
		request.getRequestURI();
		String no = ((TeacherUser) request.getSession().getAttribute("user"))
				.getNo();
		mav.addObject("teacher", tservice.GetTeacherInfo(no));
		mav.addObject("title", "教师基本信息");
		return mav;
	}

	/**
	 * 教师信息修改
	 * 
	 * @param name
	 * @param tel
	 * @param qq
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateInfo")
	@ResponseBody
	public String UpdateInfo(String name, String tel, String qq,
			HttpServletRequest request) {

		boolean result = false;
		try {
			TeacherUser teacher = new TeacherUser();
			teacher.setTelephone(tel);
			teacher.setName(name);
			teacher.setQq(qq);
			teacher.setId(((BaseUser) request.getSession().getAttribute("user"))
					.getId());
			result = tservice.updateTeacherInfo(teacher);
		} catch (Exception e) {
			log.error("修改错误:" + e.getLocalizedMessage());
			e.printStackTrace();
		}
		return result ? SUCCESS : FAIL;
	}

	/**
	 * 添加题目的页面跳转
	 * 
	 * @param name
	 * @param description
	 * @param remark
	 * @return
	 */
	@RequestMapping("/publish_newProject")
	public ModelAndView ToAddNewProject(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("teacher/new_project");
		TeacherUser teacher = (TeacherUser) request.getSession().getAttribute(
				"user");
		Integer tea_id = teacher.getId();
		List<Profession> profs = tservice.getAllProfession(tea_id);
		mav.addObject("profs", profs);
		mav.addObject("title", "发布新题目");
		return mav;
	}

	@ResponseBody
	@RequestMapping("/getTeacherList")
	public List<TeacherUser> getTeacherListByTeacherId(
			HttpServletRequest request) {
		TeacherUser cur = (TeacherUser) request.getSession().getAttribute(
				"user");
		return tservice.getTeacherListByTeacherId(cur.getId(),
				cur.getDepartmentId());
	}

	/**
	 * 添加新题目
	 * 
	 * @param name
	 * @param description
	 * @param remark
	 * @param professionNames
	 * @return
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("/publish_project")
	public String AddNewProject(String name, String description,
			@RequestParam(required = false) String remark,
			@RequestParam("prof_names") String[] professionNames,
			HttpServletRequest request,
			@RequestParam("fileName") String fileName,
			@RequestParam("syteacher") Integer syteacher) {
		String message = null;
		try {
			fileName = fileName.toString();
			Project p = new Project();
			p.setStatus(Project.NOT_AUTH);
			p.setDescription(description);
			if (syteacher != 0)
				p.setShengyue_tea_id(syteacher);
			p.setRemark(remark);
			p.setName(name);
			int id = ((BaseUser) request.getSession().getAttribute("user"))
					.getId();
			p.setTea_id(id);
			p.setAttach_file(fileName);
			if (tservice.AddProject(p)) {
				int proj_id = 0;
				proj_id = p.getId();
				ProjAndProf pap = new ProjAndProf();
				for (String n : professionNames) {
					Integer prof_id = tservice.getProfessionIDByName(n);
					pap.setProf_id(prof_id);
					pap.setProj_id(proj_id);
					tservice.AddProjAndProf(pap);
				}
				message = SUCCESS;
			}
		} catch (Exception e) {
			message = FAIL;
			e.printStackTrace();
			log.info("add data failed!");
		}
		return message;
	}

	/**
	 * 删除题目
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete_project_{id}")
	public String DeleteProject(@PathVariable("id") Integer id) {
		boolean result = false;
		try {
			result = tservice.DelProject(id);
			// result = true;
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		// System.out.println(result);
		return result ? SUCCESS : FAIL;
	}

	/**
	 * 跳转至修改题目页面
	 * 
	 * @param projId
	 * @param request
	 * @return
	 */
	@RequestMapping("update_project_{id}")
	public ModelAndView toModifyProject(@PathVariable("id") Integer projId,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		Project proj = tservice.GetProjectById(projId);
//		System.out.println(proj.getShengyue_tea_id());
		mav.addObject("proj", proj);
		mav.setViewName("teacher/update_Project");
		TeacherUser teacher = (TeacherUser) request.getSession().getAttribute(
				"user");
		List<Profession> profs = tservice.getAllProfession(teacher.getId());
		mav.addObject("profs", profs);
		mav.addObject("title", "修改题目");
		return mav;
	}

	/**
	 * 更新题目
	 * 
	 * @param id
	 * @param name
	 * @param description
	 * @param remark
	 * @return
	 */
	@Transactional
	@RequestMapping("/update_project")
	@ResponseBody
	public String UpdateProject(Integer id, String name, String description,
			String remark, Integer syteacher) {
		Project p = new Project();
		p.setStatus(Project.NOT_AUTH);
		p.setDescription(description);
		p.setId(id);
		p.setName(name);
		p.setRemark(remark);
		p.setShengyue_tea_id(syteacher);
		boolean b = true;
		try {
			tservice.UpdateProject(p);
			log.info("修改题目成功");
		} catch (Exception e) {
			b = false;
			e.printStackTrace();
			log.info("修改数据失败!");
		}
		return b ? SUCCESS : FAIL;
	}

	/**
	 * 转向题目导入页面
	 * 
	 * @return
	 */
	@RequestMapping("/to_BatchAdd")
	public ModelAndView toBatchAddProject() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("title", "题目导入");
		mav.setViewName("teacher/batchAddProject");
		return mav;
	}

	/**
	 * 题目批量导入
	 * 
	 * @param request
	 * @param filePath
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchAddProject")
	public String BatchAddProject(HttpServletRequest request,
			MultipartFile filePath,String[] cols) {
		ModelAndView mav = new ModelAndView();
//		System.out.println(Arrays.toString(cols));
		List<String> colNames = new ArrayList<>();
		Properties properties = new Properties();
		try{
			properties.load(TeacherController.class.getClassLoader().getResourceAsStream("com/teacher/util/excelColumns.properties"));
		for(String col : cols){
//			System.out.println(col);
			colNames.add(properties.getProperty(col));
		}
		}catch(Exception e){
			e.printStackTrace();
			log.info("未找到列\t"+e.getLocalizedMessage());
			return "{success:false}";
		}
		Collection<Project> projects = null;
		String result = "";
		try {
			String path = ExcelUtils.Upload(filePath, request
					.getServletContext().getRealPath("/") + "importFile");
			String ExtName = ExcelUtils.getFileExtendName(path);
			projects = ExcelUtils.ReadExcel(path, ExtName.equals("xlsx") ? true
					: false,colNames, tservice,request);
			TeacherUser teacher = (TeacherUser) request.getSession()
					.getAttribute("user");
			for (Project p : projects) {
				p.setStatus(Project.NOT_AUTH);
				p.setTea_id(teacher.getId());
				tservice.AddProject(p);
				List<ProjAndProf> paps = null;
				paps = p.getProfs();
				for (ProjAndProf pap : paps) {
					pap.setProj_id(p.getId());
					tservice.AddProjAndProf(pap);
				}
			}
			result = "{success:true}";
		} catch (Exception e) {
			log.info("题目导入失败！\n" + e.getLocalizedMessage());
			result = "{success:false}";
			e.printStackTrace();
		}
		
		return result;
	}

	// 教师登录处理
	@RequestMapping("/teacher_home")
	public ModelAndView toTeacherHome(HttpServletRequest request) {
		BaseUser user = (BaseUser) request.getSession().getAttribute("user");
		int tea_id = user.getId();
		ModelAndView mav = new ModelAndView();
		mav.setViewName("teacher/teacher_home");
		List<Project> projects = tservice.getProjectsOfTeacher(tea_id);
		Map<Integer, Boolean> vis = new HashMap<>();
		mav.addObject("projects", projects);
		mav.addObject("v", vis);
		mav.addObject("title", "教师主页");
		return mav;
	}

	/**
	 * 根据用户选择的状态获取题目
	 * 
	 * @param status
	 * @param request
	 * @return
	 */
	@RequestMapping("/getProjectByStatus")
	@ResponseBody
	public List<Project> getProjectsByStatus(String status,
			HttpServletRequest request) {
		List<Project> projects = null;
		TeacherUser teacher = (TeacherUser) request.getSession().getAttribute(
				"user");
		status = StringUtils.StatusToProperty(status);
		try {
			projects = tservice.getProjectsByStatus(status, teacher.getId());
		} catch (Exception e) {
			e.printStackTrace();
			log.info("查询失败！");
		}
		return projects;
	}

	@ResponseBody
	@RequestMapping("/queryProjectByKeywordOrStatus")
	public List<Project> QueryProject(String keyword, String status,HttpServletRequest request) {
		List<Project> projects = null;
		TeacherUser user = (TeacherUser)request.getSession().getAttribute("user");
		if (!"请选择状态".equals(status)) {
			status = StringUtils.StatusToProperty(status);
		} else {
			status = null;
		}
		try {
			projects = tservice.GetProjectsByKeywordOrStatus(keyword, status,user.getId());
			log.info("查询题目成功!");
		} catch (Exception e) {
			log.info("查询失败!");
		}
		return projects;
	}

	/**
	 * 验证用户输入的旧密码是否正确
	 * 
	 * @param password
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/validatePassword")
	public String validatePassword(String password, HttpServletRequest request) {
		TeacherUser user = ((TeacherUser) request.getSession().getAttribute(
				"user"));
		String input = Md5Encrypt.encrypt(password);
		return input.equals(user.getPassword()) ? SUCCESS : FAIL;
	}

	@RequestMapping("/project_detail_{id}")
	public ModelAndView showProjecctDetail(@PathVariable("id") Integer proj_id,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		Project p = tservice.GetProjectInfoById(proj_id);
		TeacherUser user = (TeacherUser) request.getSession().getAttribute(
				"user");
		List<IntentProject> intents = tservice.GetIntentProjectByProjId(
				proj_id, user.getMaxLevel());
		mav.addObject("proj", p);
		mav.addObject("intents", intents);
		mav.setViewName("teacher/project_detail");
		mav.addObject("title", "题目明细");
		return mav;
	}

	/**
	 * 附件上传
	 * 
	 * @param attach_file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadAttachFile")
	public String UploadAttachFile(MultipartFile attach_file,
			HttpServletRequest request, HttpServletResponse response) {
		String fileName = "";
		try {
			fileName = Upload.Uploadfile(attach_file, "attachFile", request);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}

	@ResponseBody
	@RequestMapping("/selectStu")
	public String SelectStudentOfProject(
			@RequestParam("stu_id") Integer stu_id,
			@RequestParam("proj_id") Integer proj_id) {
		if (tservice.SelectStudentOfProject(stu_id, proj_id)) {
			return SUCCESS;
		} else {
			return FAIL;
		}
	}

	@RequestMapping("/cancelSel")
	public String cancelSel(Integer proj_id) {
		tservice.cancelSel(proj_id);
		return "redirect:project_detail_" + proj_id;
	}

	@RequestMapping("/progressView")
	public ModelAndView GetTeachingProgress(HttpServletRequest request) {
		TeacherUser teacher = (TeacherUser) request.getSession().getAttribute(
				"user");
		Integer tea_id = teacher.getId();
		ModelAndView mav = new ModelAndView();
		List<TeachCourse> tcs = tservice.GetTeachingProgressByTeacherId(tea_id);
//		for(TeachCourse tc : tcs){
//			System.out.println(tc.getTeacher().getName()+","+tc.getCourse().getName());
//		}
		mav.addObject("tcs", tcs);
		mav.setViewName("teacher/progressList");
		mav.addObject(TITLE, "教学计划明细");
		return mav;
	}

	@RequestMapping("/InfoQuery")
	public ModelAndView ToQueryInfo() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("teacher/showInfo");
		mav.addObject(TITLE, "信息查询");
		return mav;
	}

	/**
	 * 审阅题目
	 * @param request
	 * @return
	 */
	@RequestMapping("/authProject")
	public ModelAndView ToAuthView(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		TeacherUser curTeacher = (TeacherUser) request.getSession()
				.getAttribute("user");
		List<Project> projects = tservice.getAuthProject(curTeacher.getId());
		mav.addObject("projects", projects);
		mav.addObject(TITLE, "题目审阅");
		return mav;
	}

	@ResponseBody
	@RequestMapping("/queryInfo")
	public BaseUser QueryInfo(@RequestParam("type") String type,
			@RequestParam("keyword") String no) {
		if ("teacher".equals(type)) {
			TeacherUser teacher = tservice.GetTeacherInfo(no);
			log.info("查询教师号为"+no+"的信息");
			// System.out.println(teacher.getDepartmentId()+","+teacher.getDepartment());
			return teacher;
		} else {
			StudentUser student = tservice.getStudentInfoByNo(no);
			log.info("查询学号为"+no+"的学生信息");
			return student;
		}
	}

	@ResponseBody
	@RequestMapping("/uploadTask")
	public String uploadTask(MultipartFile taskFile,
			HttpServletRequest request, Integer proj_id) {
		String result = "";
		try {
			String filePath = Upload.Uploadfile(taskFile, "taskFile", request);
			log.info("成功上传任务书");
			if (tservice.uploadTaskBook(filePath, proj_id)) {
				result = "{success:true}";
			} else {
				result = "{success:false}";
			}
		} catch (Exception e) {
			result = "{success:false}";
//			e.printStackTrace();
			log.info("上传异常!\n错误信息:"+e.getLocalizedMessage());
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/syProj")
	public String AuthProj(String reason, String status, Integer id,Integer score) {
		int st = 0;
		if ("y".equals(status)) {
			st = 1;
		}
		boolean result = tservice.AuthProject(st, reason, id);
		return result ? SUCCESS : FAIL;
	}

	@ResponseBody
	@RequestMapping("/setReason")
	public String setReasonToNCStu(String reason, Integer intentId) {
		log.info("设置未选择学生的理由");
		return tservice.setReasonToNotChoose(reason, intentId) ? SUCCESS : FAIL;
	}
	
	@ResponseBody
	@RequestMapping("/getPlanByCourseId")
	public String getPlanByCourseId(Integer courseId,HttpServletRequest request){
		String url = tservice.getPlanByCourseId(courseId);
		url = StringUtils.transURLToLocalLocation(url, request);
		String result = null;
		try {
			String path = "";
			path = url.substring(0, url.lastIndexOf("/")+1);
			String file = url.substring(url.lastIndexOf("/")+1);
//			System.out.println(path+","+file);
			result = POIWordToHtml.wordToHtml(path, file, courseId.toString(), request);
			log.info("成功将word转换为html文件!");
		} catch (Exception e) {
			e.printStackTrace();
			log.info("word转换至html文件时发生异常。信息如下："+e.getLocalizedMessage());
		}
//		System.out.println(url);
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/upPlanBook")
	public String uploadTeachingPlan(MultipartFile tplan,
			Integer courseId,HttpServletRequest request){
		String planBookName = null;
		try {
			planBookName = Upload.Uploadfile(tplan, "teachPlan", request);
//			System.out.println(planBookName);
			log.info("成功上传课程ID为"+courseId+"的课程教学计划书");
		} catch (IllegalStateException e) {
			log.info("上传异常!\n错误信息:"+e.getLocalizedMessage());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			log.info("上传异常!\n错误信息:"+e.getLocalizedMessage());
		}
		boolean res = tservice.uploadCourseTeachingPlanBook(planBookName, courseId);
		return "{success:"+res+"}";
	}
	
	@ResponseBody
	@RequestMapping("/GetPassedProject")
	public List<Project> getPassedProjectOfTeacher(Integer id){
		return tservice.getPassedProjectOfTeacher(id);
	}
	
	@ResponseBody
	@RequestMapping("/SelectStuByTeacher")
	public String SelectStuByTeacher(Integer id,Integer stuId){
		try{
//			System.out.println(sutId+","+id);
			tservice.SelectStuByTeacher(stuId, id);
			return SUCCESS;
		}catch(Exception e){
			return FAIL;
		}
	}
	
	@RequestMapping("/downloadDocView")
	public ModelAndView showDownloadDocView(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		TeacherUser user = (TeacherUser)request.getSession().getAttribute("user");
		mav.addObject(TITLE,"文档下载");
		mav.setViewName("teacher/DocDownload");
		List<Project> projects = tservice.getPassedProjectOfTeacher(user.getId());
		projects = tservice.getProjectsOfTeacher(user.getId());
		mav.addObject("projects", projects);
		return mav;
	}
	
	@RequestMapping("/ScoreView")
	public String showScoreView(HttpServletRequest request){
		return "redirect:downloadDocView";
	}
	
	@ResponseBody
	@RequestMapping("/setScore")
	public String setScore(Integer id,Integer sy,Integer py,Integer db,String dbmember){
		boolean res=false;
		try{
			boolean exist = tservice.existsScore(id);
//			System.out.println(exist);
			if(!exist){
			res = tservice.setScore(id, sy, py, db,dbmember,new Date());
			}else{
				res = tservice.updateScore(id, sy, py, db);
			}
			log.info("成功录入成绩");
//			System.out.println("");
		}catch(Exception e){
			e.printStackTrace();
			log.info("成绩录入失败!");
		}
		return res?"{success:true}":"{success:false,msg:'成绩录入失败'}";
	}
	
	@ResponseBody
	@RequestMapping("/export")
	public String ExportProjects(String[] cols,HttpServletRequest request){
		Map<String,Integer> exportCols = StringUtils.getCols(cols);
		List<Project> projects = tservice.GetAllProjects();
		String url = null;
		try {
			url = DBToExcel.WriteIntoExcel(request, projects, exportCols);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println(url);
		return url;
	}
	
	@ResponseBody
	@RequestMapping("/getLastResult")
	public String getLastResult(HttpServletRequest request){
		List<Project> projects = tservice.generateResult();
		String url = DBToExcel.generateScore(projects, request);
		return url;
	}
}
